package com.vanceinfo.ecados.viewer.sysorguser;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.vanceinfo.ecados.common.Helper;
import com.vanceinfo.ecados.common.IAppConstants;
import com.vanceinfo.ecados.vo.SysOrgParty;

public class OrgInput {
	
	public static String PARENT_STRING = "null";
	
	public static List<SysOrgParty> getOrgList() {
		
		String json = Helper.getContentByURL("/ecadosWEB/app2/sysOrgAction_listAllOrgs.action",null,null,IAppConstants.REQUEST_MPTHED_GET);
        JSONObject jsonObj = JSONObject.fromObject(json);
        String dataListR = jsonObj.getString("dataListR");
        JSONArray array = JSONArray.fromObject(dataListR);
        
        List<SysOrgParty> orgList = new ArrayList<SysOrgParty>();
        List<SysOrgParty> cOrgList = new ArrayList<SysOrgParty>();
        SysOrgParty org = null;
        String porgId = "";
        
        for(int i=0;i<array.size();i++){
        	jsonObj = JSONObject.fromObject(array.getString(i));
        	org = new SysOrgParty();
        	org.setOrgId(jsonObj.getLong("orgId"));
        	org.setSname(jsonObj.getString("sname"));
        	porgId = jsonObj.getString("porgId");
        	org.setPorgId(porgId.equals(PARENT_STRING)?null:Long.parseLong(porgId));
        	org.setBnkcode(jsonObj.getString("bnkcode"));
        	org.setLname(jsonObj.getString("lname"));
        	orgList.add(org);
        }
        
        for(SysOrgParty orgEntry:orgList){
        	if(orgEntry.getPorgId()==null){
        		orgEntry.setParent(null);
        	}else{
                for(SysOrgParty pOrgEntry:orgList){
                	if(pOrgEntry.getOrgId()==orgEntry.getPorgId()){
                		orgEntry.setParent(pOrgEntry);
                		cOrgList = pOrgEntry.getChildren();
                		if(cOrgList==null) cOrgList = new ArrayList<SysOrgParty>();
                		cOrgList.add(orgEntry);
                		pOrgEntry.setChildren(cOrgList);
                		break;
                	}
                }
        	}
        }
        
        List<SysOrgParty> list = new ArrayList<SysOrgParty>();
        for(SysOrgParty orgEntry:orgList){
        	if(orgEntry.getPorgId()==null){
        		list.add(orgEntry);
        		break;
        	}
        }
        
		return list;
	}
	
}
